/*
 * File:   Ind.cpp
 * Author: joseluis
 *
 * Created on 11 de diciembre de 2012, 18:08
 */

#include "Ind.h"
#include <iostream>
using namespace std;

Ind::Ind() {
    ui.setupUi(this);
    _IF = new InvertedFile();
    _index = new DocTerms();
}

Ind::Ind(int argc, char *argv[]) {
    AgentDB::getAgentePtr()->create_database(argc, argv);

    ui.setupUi(this);
    _IF = new InvertedFile();
    _index = new DocTerms();
}

Ind::~Ind() {
}

void Ind::on_addFile_clicked() {
    QStringList files = QFileDialog::getOpenFileNames(this, tr("Open File"), "", tr("Documents (*.txt)"));
    QStringList::Iterator it = files.begin();
    for (; it != files.end(); it++) {
        if (!list.contains(*it, Qt::CaseSensitive)) {
            list << *it;
        }
    }
    updateList();
}

void Ind::on_deleteFile_clicked() {
    if (ui.listView->selectionModel() != NULL) {
        QModelIndexList lst = ui.listView->selectionModel()->selectedIndexes();
        if (lst.count() > 0) {
            for (int i = lst.count() - 1; i > -1; i--) {
                list.removeAt(lst.at(i).row());
            }
            updateList();
        }
    }
}

void Ind::on_indexFiles_clicked() {
    string text = "";
    while (!list.isEmpty()) {
        string file = list.takeFirst().toStdString();
        text.append("File:: " + file + " --> OK\n");
        _index = analyze(file);

        // Añadir copia del documento al directorio
        fstream f(file.c_str(), fstream::in | fstream::binary);
        f << noskipws;
        istream_iterator<unsigned char> begin(f);
        istream_iterator<unsigned char> end;

        file = file.substr(file.find_last_of("/") + 1);
        file = "./docs/" + file;

        fstream f2(file.c_str(),
                fstream::out | fstream::trunc | fstream::binary);
        ostream_iterator<char> begin2(f2);

        copy(begin, end, begin2);

        _IF->addDoc(_index, file);
        ui.feedback->setText(text.c_str());

        if (_IF->getDictSize() >= 9000) _IF->toPersist();
    }
    if (_IF->getDictSize() >= 1) _IF->toPersist();
    updateList();
}

void Ind::updateList() {
    QStringListModel* model = new QStringListModel();
    model->setStringList(list);
    ui.listView->setModel(model);
}